package link_list

// https://leetcode.cn/problems/remove-nth-node-from-end-of-list/ leetcode-19
func removeNthFromEnd0(head *ListNode, n int) *ListNode {
	m := make([]*ListNode, 0)
	for node := head; node != nil; node = node.Next {
		m = append(m, node)
	}

	length := len(m)
	delete := length - n
	if delete == 0 {
		return head.Next
	}

	prev := m[delete-1]
	var next *ListNode
	if delete+1 < length {
		next = m[delete+1]
	}
	prev.Next = next
	return head
}

func removeNthFromEnd1(head *ListNode, n int) *ListNode {
	first, second := head, head
	for count := 0; count < n-1; count++ {
		first = first.Next
	}

	var prev *ListNode

	for ; first.Next != nil; first = first.Next {
		if prev == nil {
			prev = head
		} else {
			prev = second
		}
		second = second.Next
	}
	if prev == nil {
		return head.Next
	}

	prev.Next = second.Next
	return head
}
